#!/usr/bin/env bash
# This script configure SSL, htaccess and start our NGINX webserver
# service.

# Defaults
SSL_HOME='/opt/local/etc/nginx/ssl/'
SVC_NAME='svc:/pkgsrc/nginx:default'

# Create folder if it doesn't exists
mkdir -p "${SSL_HOME}"

# Self-signed certificate generator
/opt/itime/bin/ssl-selfsigned.sh -d ${SSL_HOME} -f nginx

# Enable NGINX webserver service
svcadm enable ${SVC_NAME}

# Try to provide Let's Encrypt SSL certificate
/opt/itime/bin/ssl-generator.sh ${SSL_HOME} nginx_ssl nginx ${SVC_NAME}


ARG_NAME=https_port
ARG_VALUE=443
if /usr/sbin/mdata-get ${ARG_NAME} 1>/dev/null 2>&1; then
    ARG_VALUE=$(/usr/sbin/mdata-get ${ARG_NAME})
    if [ "${ARG_VALUE}" != "443" ]; then
        log "set https port"
        gsed -i "s/:443/:${ARG_VALUE}/g" /opt/local/etc/nginx/nginx.conf
    fi
fi

ARG_NAME=ssl_domain
if /usr/sbin/mdata-get ${ARG_NAME} 1>/dev/null 2>&1; then
    ARG_VALUE=$(/usr/sbin/mdata-get ${ARG_NAME})
    log "set ssl domain"
    gsed -i "s/server_name _;/server_name ${ARG_VALUE};/g" /opt/local/etc/nginx/nginx.conf
fi

# Restart NGINX webserver service
svcadm restart ${SVC_NAME}